//
// web ui
// Make any .NET app a Web Server « Brian Nickel’s Online Journal <http://kerrick.wordpress.com/2007/06/12/make-any-net-app-a-web-server/> 
//
import System
import System.IO
import Banshee.ServiceStack
import Banshee.MediaEngine
import Mono.Unix
import System.Reflection

import Boo.Lang.Compiler
import Boo.Lang.Compiler.IO
import Boo.Lang.Compiler.Pipelines
import Boo.Lang.Interpreter

def CombineMultiplePath( *paths as (string) ):
	result=""
	for path in paths:
		result=Path.Combine( result, path )
	return result

class XspServer:
	protected ConfigurationName as string:
		get:
			return "WebServer"
	
	public DisplayName as string:
		get:
			return "XSP Web Server"
			
	public Description as string:
		get:
			return "A sample web server running within banshee."
			
	_server = null

	def constructor():
		Hyena.Log.Information( "Initializing XSP" )

		// create BansheePlayer from webui-common.dll
		myDocuments = Environment.GetFolderPath( Environment.SpecialFolder.MyDocuments )
		outputBinaryPath = CombineMultiplePath( myDocuments, ".config", "banshee-1", "boo-scripts", "webui", "bin" )
		commonAssembly = Assembly.LoadFrom( Path.Combine( outputBinaryPath, "webui-common.dll" ) )
		query = Activator.CreateInstance( commonAssembly.GetType( "BansheePlayer" ) )
		GC.KeepAlive( query )

		// create Xsp server from Mono.WebServer2.dll
		webServer2Assembly = Assembly.LoadFrom( Path.Combine( System.Runtime.InteropServices.RuntimeEnvironment().GetRuntimeDirectory(), "Mono.WebServer2.dll") )
		webSourceArgs = ( System.Net.IPAddress.Any, 8080 )
		source = Activator.CreateInstance( webServer2Assembly.GetType( "Mono.WebServer.XSPWebSource" ), *webSourceArgs )

		serverArgs = ( source, )
		_server = Activator.CreateInstance( webServer2Assembly.GetType( "Mono.WebServer.ApplicationServer" ), *serverArgs )
		appPath = CombineMultiplePath( myDocuments, ".config", "banshee-1", "boo-scripts", "webui" )
		_server.AddApplicationsFromCommandLine( "/:${appPath}" )
		_server.GetApplicationForPath( null, -1, "/", true ).AppHost.Domain.SetData( "bansheePlayer", query )
		_server.Start( true )

	def destructor():
		_server.UnloadAll()
		_server.Stop()
		Hyena.Log.Information( "Disposing XSP" )

xspServer = null

def OnClientStarted( client as Client ):
	xspServer = XspServer()

Hyena.Log.Information( "webui-run script is loaded." )

Banshee.ServiceStack.Application.ClientStarted += OnClientStarted

